package cn.cellcom.agent.online.handler;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.j2ee.AgentListener;
import cn.cellcom.agent.pojo.TTrace;
import cn.cellcom.jar.util.AU;
import cn.cellcom.jar.util.IDGenerator;
import cn.cellcom.jar.util.MyException;

/**
 * 
 * @author zhengyj
 * 
 */
public class TraceHandler {
	private static Logger log = LoggerFactory.getLogger(TraceHandler.class);

	/**
	 * 记录轨迹，可能存到内存，也可以直接存入mongodb，取决于是否有crm信息存在session[也就是是否访问了坐席]
	 * 
	 * @param cid
	 * @param random
	 * @param pageTitle
	 * @param pageUrl
	 * @param org
	 * @param pid
	 */
	public static void record(String org, String pid, HttpServletRequest req, HttpServletResponse rep) {
		String pageTitle = null;
		String pageUrl = null;
		try {
			pageTitle = URLDecoder.decode(req.getParameter("pageTitle"), "UTF-8");
			pageUrl = URLDecoder.decode(req.getParameter("pageUrl"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
		}
		String cid = (String) req.getSession().getAttribute(AgentConstant.CRM_ID_IN_SESSION);

		try {
			List<TTrace> list = (List<TTrace>) req.getSession().getAttribute("traces");
			if (list == null) {
				list = new ArrayList<TTrace>();
				req.getSession().setAttribute("traces", list);
			}
			TTrace trace = new TTrace();
			trace.setCreateTime(System.currentTimeMillis());
			trace.setId(IDGenerator.getDefaultUUID());
			trace.setOrg(org);
			trace.setPid(pid);
			trace.setTitle(pageTitle);
			trace.setUrl(pageUrl);
			trace.setRequestAgent(AgentConstant.NO);
			trace.setHttpSessionId(req.getSession().getId());
			trace.setIp(req.getRemoteAddr());
			if (cid != null) {
				trace.setCrm(cid);
				trace.setLogon(AgentConstant.YES);
				AgentListener.getMgDao().mySave(trace);
			} else {
				trace.setLogon(AgentConstant.NO);
				list.add(trace);
			}
		} catch (MyException e) {
			log.error("", e.getException());
		}
	}

	/**
	 * 将临时的记录写入mongodb
	 * 
	 * @param cid
	 * @param random
	 */
	public static void saveTempRecordToMongoDb(String cid, HttpSession httpSession) {
		try {
			List<TTrace> list = (List<TTrace>) httpSession.getAttribute("traces");
			if (AU.isNotBlank(list)) {
				for (int i = 0; i < list.size(); i++) {
					TTrace trace = list.get(i);
					trace.setCrm(cid);
					AgentListener.getMgDao().mySave(trace);
				}
				list.clear();
			}
		} catch (MyException e) {
			log.error(cid + " catch exception while save trace.", e.getException());
		}
	}

	/**
	 * 更新最后一个标记为访问坐席
	 * 
	 * @param pid
	 * @param cid
	 * @param httpSessionId
	 * @return
	 */
	public static TTrace updateLastRecord(String pid, String cid, String httpSessionId) {
		try {
			String hql = "from " + TTrace.class.getCanonicalName() + " where (pid = ?) and (crm = ?) order by createTime desc";
			List list = AgentListener.getMgPageDao().myList(hql, new String[] { pid, cid }, 1, 1);
			if (AU.isNotBlank(list)) {
				TTrace last = (TTrace) list.get(0);
				if (last.getHttpSessionId().equals(httpSessionId)) {
					last.setRequestAgent(AgentConstant.YES);
					AgentListener.getMgDao().myUpdate(last);
				}
				return last;
			}
		} catch (MyException e) {
			log.error(cid + " catch exception while update trace.", e.getException());
		}
		return null;
	}

	public static TTrace getTraceById(String trace) throws MyException {
		return (TTrace) AgentListener.getMgDao().myGet(TTrace.class, trace);
	}
}
